<?php
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * 微信消息管理
 */
class Wx_msg extends CI_Controller {

    function __construct() {
        parent::__construct();

        include_once APPPATH . '/third_party/wechat/wxmsg/WxMsg.php';
        include_once APPPATH . '/third_party/wechat/wxmsg/WxTextDispatcher.php';
    }

    public function index() {
        if (isset($_GET["echostr"])) {//接入模式
            $check = $this->check_signature();
            if ($check) {
                echo $_GET["echostr"];
            } else {
                echo 'error';
            }
        } else {//自动回复
            $request_type = WxMsg::get_request_type();
            switch ($request_type) {
                case 'text'://文本消息
                    $this->_handle_text_message();
                    break;
                case 'event'://事件
                    $this->_handle_event_message();
                    break;
                default :
                    WxMsg::fetch_text_result("没有理解您发送的内容");
                    break;
            }
        }
    }

    //处理文字信息
    private function _handle_text_message() {
        $message = WxMsg::get_request();
        $return_message = WxTextDispatcher::dispatch(trim($message['Content']));
        WxMsg::fetch_text_result($return_message);
    }

    //处理事件消息
    private function _handle_event_message() {
        $message = WxMsg::get_request();
        switch (strtoupper($message['Event'])) {
            case 'CLICK':
                //菜单消息的EventKey当做TextDispatcherConfig中的文字内容，通过TextDispatcher转发
                WxMsg::set_request('MsgType', 'text');
                WxMsg::set_request('Content', $message['EventKey']);
                $return_message = WxTextDispatcher::dispatch($message['EventKey']);
                WxMsg::fetch_text_result($return_message);
                break;
            case 'SUBSCRIBE':
                if ($message['EventKey']) {
                    //处理未关注时扫描的带参数二维码
                }
                //处理订阅事件
                break;
            case 'UNSUBSCRIBE':
                //处理取消订阅事件
                break;
            case 'SCAN':
                //处理已关注时扫描的带参数二维码
                break;
            case 'LOCATION':
                //处理上报的地理位置信息
                break;
        }
        //全部不匹配的时候返回的内容
        WxMsg::fetch_text_result("感谢订阅");
    }

    /**
     * 验证token
     */
    private function check_signature() {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = WEIXIN_TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

}
